package com.dyh.quickdemozwei.dyhTp;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yhdong
 * @Date: 2021/10/1 17:23
 */
@Slf4j
public class TestDyhIsolateThreadPool {

    Runnable r = ()->{
        log.info("开始 {}",Thread.currentThread().getName());
        try {
            Thread.sleep(1500L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("结束 {}",Thread.currentThread().getName());
    };

    /*1.xs*/
    @Test
    public void test() throws InterruptedException {
        List<Foo> data = Lists.newArrayList(
                new Foo("A"),new Foo("A"),new Foo("A"),new Foo("B"),new Foo("B"),new Foo("C"),new Foo("B"),
                new Foo("A")
        );

        int diff = 4;
        List<Foo> [] diffData = diff(data,diff);
        DyhIsolateThreadPool dyhIsolateThreadPool = new DyhIsolateThreadPool(diff);
        for(int idx=0;idx<diffData.length;idx++){
            for (Foo foo : diffData[idx]) {
                dyhIsolateThreadPool.getPool(idx).execute(r);
            }

        }

        Thread.sleep(60000);

        System.out.println();
    }

    /*3s*/
    @Test
    public void testBefore() throws InterruptedException {
        List<Foo> data = Lists.newArrayList(
                new Foo("A"),new Foo("A"),new Foo("A"),new Foo("B"),new Foo("B"),new Foo("C"),new Foo("B"),
                new Foo("A")
        );

        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                4,12,120, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1),
                new ThreadFactoryBuilder().setNameFormat("normal-%d").build(),
                //   new ThreadPoolExecutor.CallerRunsPolicy()
                new ThreadPoolExecutor.AbortPolicy()
        );

        for (Foo datum : data) {
            poolExecutor.execute(r);
        }

        Thread.sleep(60000);

        System.out.println();
    }

    List<Foo> [] diff(List<Foo> datas,int diff){
        List<Foo> [] matrix = new List[diff];
        for (int i = 0; i<diff;i++){
            matrix[i]=new ArrayList<>();
        }

        String lastRouteKey = "";
        int lastRouteIdx = 0;
        for (Foo datum : datas) {
            if (!lastRouteKey.equals("")&&lastRouteKey.equals(datum.getCode()))
                lastRouteIdx=(lastRouteIdx+1)&(diff-1);

            // lastRouteIdx=(lastRouteIdx+1)%diff;
            matrix[lastRouteIdx].add(datum);
            lastRouteKey = datum.getCode();
        }

        return matrix;
    }
}
